/*
 * Created on 2005-9-30
 *
 */
package com.hd123.rumba.runtime;

import java.util.HashMap;

import org.apache.log4j.Logger;

import com.hd123.rumba.exception.BusinessException;

/**
 * @author caili
 */
public class NamingMgr {
  private static NamingMgr instance = null;
  private HashMap managers = new HashMap();
  private HashMap managerRegistry = new HashMap();
  private Logger logger;

  private NamingMgr() {
    logger = Logger.getLogger(this.getClass());
  }

  public synchronized static NamingMgr getInstance() {
    if (instance == null) {
      instance = new NamingMgr();
    }
    return instance;
  }

  public synchronized void registerManager(String intfName, String implName) {
    managerRegistry.put(intfName, implName);
    logger.info(intfName + "->" + implName);
    try {
      this.lookupMgr(Class.forName(intfName));
    } catch (Exception e) {
      logger.error("未被验证的管理员接口与实现类：[" + intfName + ", " + implName + "]。", e);
    }
  }

  /**
   * 返回单实例
   * 
   * @param intf
   * @return
   * @throws BusinessException
   */
  public Object lookupMgr(Class intf) throws BusinessException {
    Object mgr = managers.get(intf);
    if (mgr == null) {
      String className = (String) managerRegistry.get(intf.getName());
      if (className != null)
        try {
          mgr = Class.forName(className).newInstance();
          managers.put(intf, mgr);
        } catch (Exception e) {
          throw new BusinessException(e);
        }
    }
    return mgr;
  }

  public void reset() {
    managers.clear();
  }
}
